package animix.blue.server.user.controller;

import animix.blue.server.common.bean.pojo.LogOperationAnno;
import animix.blue.server.common.bean.pojo.Result;
import animix.blue.server.user.service.RoleRightService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@Api(description = "角色权限关系管理API")
public class RoleRightController {

    @Autowired
    private RoleRightService roleRightService;

    @ApiOperation(value = "获取角色权限", notes = "根据角色id获取角色权限")
    @ApiImplicitParam(name = "roleId", value = "角色id", required = true, dataType = "Int")
    @GetMapping("/role/{roleId}/right")
    public Result getByRoleId(@PathVariable Integer roleId) {
        return roleRightService.getRightIdsByRoleId(roleId);
    }

    @LogOperationAnno(action="设置", object="角色权限")
    @ApiOperation(value = "设置角色权限", notes = "根据角色id设置角色权限")
    @ApiImplicitParam(name = "roleId", value = "角色id", required = true, dataType = "Int")
    @PutMapping("/role/{roleId}/right")
    public Result setByRoleId(@PathVariable Integer roleId, @RequestBody Map<String, Object> para) {
        Integer[] rightIds = getRightIdsFromMap(para);
        return roleRightService.setByRoleId(roleId, rightIds);
    }

    private Integer[] getRightIdsFromMap(Map<String, Object> para) {
        List idList = (List<Integer>) para.get("rightIds");
        if (idList != null && idList.size() > 0) {
            Integer[] ids = new Integer[idList.size()];
            for (int i = 0; i < idList.size(); i++) {
                ids[i] = (Integer) idList.get(i);
            }
            return ids;
        } else {
            return null;
        }
    }
}
